from fastapi import APIRouter, HTTPException, Request,FastAPI
from pydantic import BaseModel, Field
from app.services.ip_location_service import get_ip_location
from app.utils.response_handler import SuccessResponse
from datetime import datetime
import logging
import traceback
# import geoip2.database
import os


# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
router = APIRouter(prefix="/api/v1")

# 临时注释掉GeoIP数据库初始化，以避免路径问题
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# GEOIP_PATH = os.path.join(BASE_DIR, "app", "conf", "GeoLite2-Country.mmdb")
# GEOIP_READER = geoip2.database.Reader(GEOIP_PATH)
GEOIP_READER = None

def get_public_ip(request: Request) -> str:
    """提取客户端真实公网IP（优化代理场景适配）"""
    # 1. 优先读取代理透传的公网IP（最常用场景）
    x_forwarded_for = request.headers.get("X-Forwarded-For")
    if x_forwarded_for:
        # 过滤可能的私有IP，只取第一个公网IP（避免代理链中的内网IP）
        for ip in x_forwarded_for.split(","):
            ip = ip.strip()
            if not (ip.startswith("10.") or ip.startswith("172.0.") or ip.startswith("192.168.")):
                return ip

    # 2. 读取 X-Real-IP 透传的IP
    x_real_ip = request.headers.get("X-Real-IP")
    if x_real_ip and not (x_real_ip.startswith("10.") or x_real_ip.startswith("172.0.") or x_real_ip.startswith("192.168.")):
        return x_real_ip

    # 3. 无代理时直接获取公网IP（服务需部署在公网）
    client_ip = request.client.host
    return client_ip

@router.get("/ip-info")
async def get_ip_geoinfo(request: Request) -> dict:
    """获取公网IP并解析地理信息"""
    public_ip = get_public_ip(request)
    print(public_ip)

    try:
        if GEOIP_READER:
            geo_data = GEOIP_READER.country(public_ip)
            return {
                "public_ip": public_ip,
                "country": {
                    "code": geo_data.country.iso_code,
                    "name": geo_data.country.name
                },
                "is_private_ip": public_ip.startswith(( "172.0.", "192.168."))  # 标记是否为私有IP
            }
        else:
            # GeoIP功能暂时不可用
            return {
                "public_ip": public_ip,
                "country": {"code": "N/A", "name": "GeoIP功能暂时不可用"},
                "is_private_ip": public_ip.startswith(( "172.0.", "192.168."))
            }
    except Exception as e:
        return {"public_ip": public_ip, "error": f"解析失败：{str(e)}"}

# 请求体模型
class IPLocationRequest(BaseModel):
    ip_address: str = Field(..., description="需要查询的IP地址")
    shop_domain: str = Field(..., description="店铺域名")
    access_time: datetime = Field(default_factory=datetime.now, description="访问时间")


@router.post("/ip-location", response_model=SuccessResponse)
async def get_ip_location_info(req_data: IPLocationRequest):
    """IP地址地理位置查询接口"""
    try:
        logging.info(
            f"IP查询请求: IP={req_data.ip_address}, 店铺={req_data.shop_domain}, 时间={req_data.access_time}"
        )

        # 调用IP地理位置查询服务
        location_info = get_ip_location(req_data.ip_address)

        # 构建响应数据，包含入参信息和地理位置信息
        response_data = {
            "ip_address": req_data.ip_address,
            "shop_domain": req_data.shop_domain,
            "access_time": req_data.access_time.strftime("%Y-%m-%d %H:%M:%S"),
            "location_info": location_info
        }

        logging.info(f"IP查询结果: {response_data}")
        return SuccessResponse(data=response_data)

    except Exception as e:
        logging.error(f"处理IP查询请求出错: {e}\n{traceback.format_exc()}")
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )